package httpfs

import (
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"
)

var (
	JSONEscapeFunc func(str string) string
)

// logf prints to the ErrorLog of the *Server associated with request r
// via ServerContextKey. If there's no associated server, or if ErrorLog
// is nil, logging is done via the log package's standard logger.
func logf(r *http.Request, format string, args ...interface{}) {
	s, _ := r.Context().Value(http.ServerContextKey).(*http.Server)
	if s != nil && s.ErrorLog != nil {
		s.ErrorLog.Printf(format, args...)
	} else {
		log.Printf(format, args...)
	}
}

func DateTimeString(val time.Time) string {
	return val.Format("2006-01-02 15:04:05")
}

type handfun func(http.ResponseWriter, *http.Request) bool

var (
	size_kb int64 = 1024
	size_mb       = 1024 * size_kb
	size_gb       = 1024 * size_mb
	size_tb       = 1024 * size_gb
)

func HumanFilesize(sizebytes int64) string {

	osize := sizebytes

	rval := ""

	t := float64(sizebytes) / float64(size_tb)
	if t > 1 {
		rval = fmt.Sprintf("%.2f TB ", t)
		return rval
	}

	t = float64(sizebytes) / float64(size_gb)
	if t > 1 {
		rval = fmt.Sprintf("%.2f GB ", t)
		return rval
	}

	t = float64(sizebytes) / float64(size_mb)
	if t > 1 {
		rval = fmt.Sprintf("%.2f MB ", t)
		return rval
	}

	t = float64(sizebytes) / float64(size_kb)
	if t > 1 {
		rval = fmt.Sprintf("%.2f KB ", t)
		return rval
	}

	return fmt.Sprintf("%d B", osize)
}

func HumanFilesizeEx(sizebytes int64) string {

	osize := sizebytes

	rval := ""

	t := sizebytes / size_tb
	if t > 0 {
		rval = fmt.Sprintf("%d TB ", t)
	}
	sizebytes = sizebytes % size_tb

	t = sizebytes / size_gb
	if t > 0 {
		rval = fmt.Sprintf("%s%d GB ", rval, t)
	}

	sizebytes = sizebytes % size_gb
	t = sizebytes / size_mb
	if t > 0 {
		rval = fmt.Sprintf("%s%d MB ", rval, t)
	}

	sizebytes = sizebytes % size_mb
	t = sizebytes / size_kb
	if t > 0 {
		rval = fmt.Sprintf("%s%d KB ", rval, t)
	}

	sizebytes = sizebytes % size_kb
	if sizebytes > 0 {
		rval = fmt.Sprintf("%s%d B ", rval, sizebytes)
	}

	if len(rval) == 0 {
		return fmt.Sprintf("%d B", osize)
	}

	return strings.TrimSpace(rval)
}

var htmlReplacer = strings.NewReplacer(
	"&", "&amp;",
	"<", "&lt;",
	">", "&gt;",
	// "&#34;" is shorter than "&quot;".
	`"`, "&#34;",
	// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
	"'", "&#39;",
)
